package org.smart4j.framework.helper;

import org.apache.commons.lang3.ArrayUtils;
import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.CollectionUtil;
import org.smart4j.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;


/**
 * @author djw
 * @time 2017/10/24 14:44
 */
public final class IocHelper {
    static {
        Map<Class<?>,Object> beanMap=BeanHelper.getBeanMap();
        if(CollectionUtil.isNotEmpty(beanMap)){
            for(Map.Entry<Class<?>,Object> beanEntry:beanMap.entrySet()){
                Class<?> beanClass=beanEntry.getKey();
                Object beanInstance=beanEntry.getValue();

                Field[] fields=beanClass.getDeclaredFields();
                if(ArrayUtils.isNotEmpty(fields)){
                    for(Field field:fields){
                        if(field.isAnnotationPresent(Inject.class)){
                            Class<?> beanFieldClass=field.getType();
                            Object beanFieldInstance=beanMap.get(beanFieldClass);
                            if(beanFieldInstance!=null){
                                ReflectionUtil.setField(beanFieldInstance,field,beanFieldInstance);
                            }
                        }
                    }
                }
            }

        }
    }
}
